/*********************************************************************************
 *      Copyright:  (C) 2025 iot25<lingyun@email.com>
 *                  All rights reserved.
 *
 *       Filename:  server_main_2.0.c
 *    Description:  This file server_main_2.0.c
 *                 
 *        Version:  1.0.0(13/05/25)
 *         Author:  iot25 <lingyun@email.com>
 *      ChangeLog:  1, Release initial version on "13/05/25 22:18:57"
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <ctype.h>
#include <time.h>
#include <pthread.h>
#include <getopt.h>
#include <libgen.h>
#include <sys/types.h>   
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/epoll.h>
#include <sys/resource.h>

#include"server_main_2.0.h"
#include"logger.h"
#include"sqlite_database.h"

#define _LOG_LOCK_     		1
#define _LOG_FILENAME_ 		"logger.log"
#define MAX_EVENTS          512
#define ARRAY_SIZE(x)       (sizeof(x)/sizeof(x[0]))

//main函数
int main(int argc, char **argv)
{
    int                       listenfd, connfd;
    int                       serv_port = 0;
    int                       daemon_run = 0;
    char                     *progname = NULL;
    int                       opt;
    int                       rv;
    int                       i;
    char                      buf[1024];
    int                       epollfd;
    struct epoll_event        event;
    struct epoll_event        event_array[MAX_EVENTS];
    int                       events;
	char					  device_id[256] = {0};
	char					  temperature[256] = {0};
	char					  sample_time[256] = {0};
	char                      db_name[] = "ds18b20_data_server";
    struct option             long_options[] =
    {   
        {"daemon", no_argument, NULL, 'b'},
        {"port", required_argument, NULL, 'p'},
        {"help", no_argument, NULL, 'h'},
        {NULL, 0, NULL, 0}
    };

	//解析当前程序的可执行文件名
    progname = basename(argv[0]);
    
	//解析命令行参数
    while ((opt = getopt_long(argc, argv, "bp:h", long_options, NULL)) != -1)
    {   
        switch (opt)
        {   
            case 'b':
                daemon_run=1;
                break;
            case 'p':
                serv_port = atoi(optarg);
                break;
            case 'h':  
                print_usage(progname);
                return EXIT_SUCCESS;
			default:
				break;
		}
	}

	//参数合法性检测
    if( !serv_port )
    {   
        print_usage(progname);
        return -1;
    }

	//启动日志文件
	log_open(_LOG_FILENAME_, LOG_LEVEL_DEBUG, 1024, _LOG_LOCK_);
	
	//创建数据库
	create_db(db_name);

	//设置最大客户端数，打破linux内核限制
    set_socket_rlimit();
    if( (listenfd = socket_server_init(NULL, serv_port)) < 0 )
    {
        log_error("ERROR: %s server listen on port %d failure\n", argv[0], serv_port);
        return -2;
    }
    log_debug("%s server start to listen on port %d\n", argv[0], serv_port);
    
	//调用程序在后台运行
    if( daemon_run )
    {
        daemon(0, 0);
    }
    if( (epollfd = epoll_create(MAX_EVENTS)) < 0 )
    {
        log_error("epoll_create() failure: %s\n", strerror(errno));
        return -3;
    }
    
	//event.events = EPOLLIN|EPOLLET;
    event.events = EPOLLIN;
    event.data.fd = listenfd;
    if( epoll_ctl(epollfd, EPOLL_CTL_ADD, listenfd, &event) < 0)
    {
        log_error("epoll add listen socket failure: %s\n", strerror(errno));
        return -4;
    }

    for ( ; ; )
    {
        //主进程
        events = epoll_wait(epollfd, event_array, MAX_EVENTS, -1);
        if(events < 0)
        {
            log_error("epoll failure: %s\n", strerror(errno));
            break;
        }
        else if(events == 0)
        {
            log_error("epoll get timeout\n");
            continue;
        }
    
		/* rv>0 is the active events count */
        for(i=0; i<events; i++)
        {
            if ( (event_array[i].events&EPOLLERR) || (event_array[i].events&EPOLLHUP) )
            {
                log_error("epoll_wait get error on fd[%d]: %s\n", event_array[i].data.fd, strerror(errno));
                epoll_ctl(epollfd, EPOLL_CTL_DEL, event_array[i].data.fd, NULL);
                close(event_array[i].data.fd);
            }
           
			/* listen socket get event means new client start connect now */
            if( event_array[i].data.fd == listenfd )
            {
                if( (connfd=accept(listenfd, (struct sockaddr *)NULL, NULL)) < 0)
                {
                    log_error("accept new client failure: %s\n", strerror(errno));
                    continue;
                }
                event.data.fd = connfd;
               
				//event.events =  EPOLLIN|EPOLLET;
                event.events =  EPOLLIN;
                if( epoll_ctl(epollfd, EPOLL_CTL_ADD, connfd, &event) < 0 )
                {
                    log_error("epoll add client socket failure: %s\n", strerror(errno));
                    close(event_array[i].data.fd);
                    continue;
                }
                log_debug("epoll add new client socket[%d] ok.\n", connfd);
            }
           
			else /* already connected client socket get data incoming */
            {
                if( (rv=read(event_array[i].data.fd, buf, sizeof(buf))) <= 0)
                {
                    log_error("socket[%d] read failure or get disconncet and will be removed.\n",
 event_array[i].data.fd);
                    epoll_ctl(epollfd, EPOLL_CTL_DEL, event_array[i].data.fd, NULL);
                    close(event_array[i].data.fd);
                    continue;
                }
                else
                {
                    log_debug("socket[%d] read get %d bytes data：%s\n", event_array[i].data.fd, rv, buf);
                   
					/* 进行数据解析 */
					sscanf(buf, "device_id:%255[^|]|Temperature:%255[^|]|SampleTime:%255[^\n]", device_id, temperature, sample_time);
					printf("%s|%s|%s\n", device_id, temperature, sample_time);
					if( (insert_data(db, device_id, temperature, sample_time)) ==0)
					{
						printf("Insert_data successfully!\n");
					}
				}
			}
		} /* for(i=0; i<rv; i++) */
	} /* while(1) */
 CleanUp:
    close(listenfd);
    return 0;
}

//命令行help函数
static inline void print_usage(char *progname)
 {
    printf("Usage: %s [OPTION]...\n", progname);
    printf(" %s is a socket server program, which used to verify client and echo back string from it\n",
 progname);
    printf("\nMandatory arguments to long options are mandatory for short options too:\n");
    printf(" -b[daemon ]  set program running on background\n");
    printf(" -p[port    ]  Socket server port address\n");
    printf(" -h[help    ]  Display this help information\n");
    printf("\nExample: %s -b -p 8900\n", progname);
    return ;
 }

//创建soket——listen——bind
int socket_server_init(char *listen_ip, int listen_port)
 {
    struct sockaddr_in        servaddr;
    int                       rv = 0;
    int                       on = 1;
    int                       listenfd;
 	 
	if ( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        log_error("Use socket() to create a TCP socket failure: %s\n", strerror(errno));
        return -1;
    }
    //允许端口
	if ( (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on))) < 0) 
	{
		log_error("setsockopt(SO_REUSEADDR) failed");
		exit(EXIT_FAILURE);
	}
    memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;   
    servaddr.sin_port = htons(listen_port);
    if( !listen_ip )  /* Listen all the local IP address */
    {
        servaddr.sin_addr.s_addr = htonl(INADDR_ANY);  
    }
    else /* listen the specified IP address  */
    {
        if (inet_pton(AF_INET, listen_ip, &servaddr.sin_addr) <= 0)
        {
            log_error("inet_pton() set listen IP address failure.\n");
            rv = -2;
            goto CleanUp;
        }
    }
    if(bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0)
    {
        log_error("Use bind() to bind the TCP socket failure: %s\n", strerror(errno));
        rv = -3;
        goto CleanUp;
    }
    if(listen(listenfd, 64) < 0)
    {
        log_error("Use bind() to bind the TCP socket failure: %s\n", strerror(errno));
        rv = -4;
        goto CleanUp;
    }
	
CleanUp:
    if(rv<0)
        close(listenfd);
    else
        rv = listenfd;
    return rv;
 }

 //打破内核限制设置最大客户端数
 void set_socket_rlimit(void)
 {
     struct rlimit limit = {0};
     getrlimit(RLIMIT_NOFILE, &limit );
     limit.rlim_cur  = limit.rlim_max;
     setrlimit(RLIMIT_NOFILE, &limit );
     log_debug("set socket open fd max count to %ld\n", limit.rlim_max);
 }

